package listeningFile

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"hotter/model"
	"hotter/variable"
	"io/ioutil"
	"log"
	"path"
	"strings"
	"time"
)

func RecursiveFolder(path string, watcher *fsnotify.Watcher)  {

	err := watcher.Add(path)
	if err != nil {
		log.Fatal(err)
	}

	files, _ := ioutil.ReadDir(path)
	for _, f := range files {
		if f.IsDir() {
			RecursiveFolder(path + "/" + f.Name(), watcher)
		}

	}
}

func ProcessFile() {

	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}
	defer watcher.Close()

	done := make(chan bool)
	//var count int8 = 0
	go func() {
		for {
			select {
			case event := <-watcher.Events:
				//log.Println("event:", event)
				//if event.Op & fsnotify.Write == fsnotify.Write {
				//	log.Println("modified file:", event.Name)
				//}

				fmt.Println("Name：", event.Name)
				fmt.Println("Op：", event.Op)

				if event.Op.String() == "CREATE" {
					//count++

					paths := strings.Split(event.Name, "\\")
					fmt.Println("paths：", paths)
					fmt.Println("len：", len(paths))

					//if count%2 == 0 {
					//	var hci = model.HeatChangeInformation{
					//		Id:            variable.W.GetId(),
					//		VersionNumber: strings.Split(paths[len(paths)-1], "_")[1],
					//		Remarks:       "热更包上传",
					//		Platform:      paths[2],
					//		FileName:      event.Name,
					//		CreatedAt:     time.Now(),
					//		UpdatedAt:     time.Now(),
					//	}
					//	variable.Db.Create(&hci)
					//}

					filenameWithSuffix := path.Base(event.Name)
					fileSuffix := path.Ext(filenameWithSuffix)
					filenameOnly := strings.TrimSuffix(filenameWithSuffix, fileSuffix)

					var hci = model.HeatChangeInformation{
						Id:            variable.W.GetId(),
						VersionNumber: strings.Split(filenameOnly, "_")[2],
						Remarks:       "热更包上传",
						Platform:      paths[2],
						FileName:      event.Name,
						CreatedAt:     time.Now(),
						UpdatedAt:     time.Now(),
					}
					variable.Db.Create(&hci)

				}

				//nginx()

			case err := <-watcher.Errors:
				log.Println("error:", err)
			}
		}
	}()

	RecursiveFolder("F:/hot_change", watcher)

	//err = watcher.Add("F:/hot_change/android")
	//err = watcher.Add("F:/hot_change/ios")
	//if err != nil {
	//	log.Fatal(err)
	//}

	//err = watcher.Add("/path/to/file2") //也可以监听文件夹
	//if err != nil {
	//	log.Fatal(err)
	//}

	<-done

}

//func nginx() {
//	cmd := exec.Command("/usr/local/bin/lunchy", "restart", "nginx") //重启命令根据自己的需要自行调整
//	cmd.Run()
//}
















